package com.miui.systemui.tools

import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

object FigmaAPI {
    private const val BASE_URL = "https://api.figma.com/v1/files/"
    private var ACCESS_TOKEN = ""// 替换为您的 Token

    /**
     * 访问 Figma API 获取文件或节点信息
     *
     * @param fileId 文件 ID
     * @param nodeId 节点 ID（可选，传 null 则获取整个文件）
     * @return JSON 响应字符串
     * @throws Exception 如果请求失败或解析错误
     */
    @Throws(Exception::class)
    fun fetchFigmaData(fileId: String, nodeId: String?): String {

        ACCESS_TOKEN = Figma2xmlSettings.getSettingsInstance().mToken
        println("token: "+ ACCESS_TOKEN)

        // 拼接 URL
        var urlString = BASE_URL + fileId
        if (!nodeId.isNullOrEmpty()) {
            urlString += "?ids=$nodeId"
        }

        // 创建 URL 对象
        val url = URL(urlString)

        System.err.println("urlString:  $urlString")

        // 打开连接
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "GET"
        connection.setRequestProperty("Host", "api.figma.com")
        connection.setRequestProperty("X-Figma-Token", ACCESS_TOKEN)

        // 检查响应码
        val responseCode = connection.responseCode
        if (responseCode != 200) {
            throw RuntimeException("HTTP GET Request Failed with Error Code: $responseCode")
        }

        // 读取响应
        val `in` = BufferedReader(InputStreamReader(connection.inputStream))
        var inputLine: String?
        val response = StringBuilder()
        while ((`in`.readLine().also { inputLine = it }) != null) {
            response.append(inputLine)
        }
        `in`.close()

        return response.toString()
    }
}
